#!/usr/bin/env python3
# coding:utf-8

'''
'''

import os
import os.path
import shutil

from getpath import PathList

def path_iter(path_list,target_dir):
    '''Iterative generation of paths contained in path_list.
    path_list:a object of PathList,that contain all the paths info.
    target_dir:the target dir of files.
    
    return: will return a tuple (source_path,dest_path,dest_path_dir,index_in_path_list) 
    '''
    for index,ever_path in enumerate(path_list.getPathList()):
        dest_path = ever_path['d_path']
        new_path = os.path.join(target_dir,dest_path)
        source_file = os.path.join(ever_path['s_dir'],ever_path['s_file'])
        dest_file = os.path.join(new_path,ever_path['s_file'])
        yield source_file,dest_file,new_path,index

def copy_files(path_list,target_dir):
    '''Copy the file according to the path information of the file in path_list.
    path_list:a object of PathList,that contain all the paths info.
    target_dir:the target dir of files.
    '''
    for path_info in path_iter(path_list,target_dir):
        new_path = path_info[2]
        if not os.path.exists(new_path):
            os.makedirs(new_path)
        source_file = path_info[0]
        dest_file = path_info[1]
        print('Copy:')
        print('from:{}'.format(source_file))
        print('to:{}'.format(dest_file))
        shutil.copyfile(source_file,dest_file)

def sync_files(path_list,target_dir,confirm=True):
    '''Comparing the time stamps of files to determine whether synchronous updates are needed.
    path_list:a object of PathList,that contain all the paths info.
    target_dir:the target dir of files.
    '''
    for path_info in path_iter(path_list,target_dir):
        source_file = path_info[0]
        dest_file = path_info[1]
        s_hash = hash(open(source_file,'rb').read())
        d_hash = hash(open(dest_file,'rb').read())
        if s_hash != d_hash:
            print('find change:')
            print(' source file:{}'.format(source_file))
            print(' dest file:{}'.format(dest_file))
            if confirm:
                opt = input('Update the destnation(Y/N):')
                if opt != 'y' and opt != 'Y':
                    continue
            print('update dest:{}'.format(dest_file))
            shutil.copyfile(source_file,dest_file)



if __name__ == "__main__":
    if os.sys.platform == 'linux':
        file_config_path = 'filespath_linux.xlsx'
        target_dir = '/media/yzh/通用盘/outdata/'
    else:
        file_config_path = 'filespath_windows.xlsx'
        target_dir = 'F:\\outdata\\'
    
    pl = PathList(file_config_path)
    #copy_files(pl,target_dir)
    sync_files(pl,target_dir)
